﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using SCSService;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace SCS.Core.Controllers
{
    public class ArticaleMasterController:BaseController
    {
        public ActionResult Index()
        {
            return RedirectToAction("ListArticleCategory");
        }

        #region "ArticleCategory"
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AddArticleCategory()
        {
            var category = new Models.Collection.ArticleCategoryCollection();
            category.CategoriesActive = true;
            int siteGuid = GetSiteGuid();
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());


            ViewData["IsAdd"] = true;
            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", languageId);
            ViewData["ListParent"] = new SelectList(GetListArticleCategoryDropBasic(null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid,null), "CategoriesID", "CategoriesName");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailArticleCategory", category);      ///Return to view detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAdd(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var category = new Models.Collection.ArticleCategoryCollection();
            TryUpdateModel(category);
            int cateId = 0;
            try
            {

                //Create ArticleCategory
                SCSService.Article_Category cate = new Article_Category();
                cate.CategoriesName = category.CategoriesName;
                if (category.CategoriesName != string.Empty)
                {
                    string inputString =baseSvc.ConvertString(category.CategoriesName);
                    Regex re = new Regex("[;\\\\/:*?\"<>|&']");
                    string outputString = re.Replace(inputString, "-");
                    cate.CategoriesAlias = outputString;
                
                }
                if (category.CategoriesAccess != null)
                {
                    cate.CategoriesAccess = (int)category.CategoriesAccess;
                }
                else
                {
                    cate.CategoriesAccess = 0;
                }

                cate.CategoriesParams = category.CategoriesParams;
                if (category.CategoriesOrdering == null)
                {
                    cate.CategoriesOrdering = Models.ArticaleMasterModel.GetCountArticleCategory(LanguageID, GetSiteGuid()) + 1 ;
                }
                else
                {
                    cate.CategoriesOrdering = (int)category.CategoriesOrdering;    
                }

                cate.CategoriesActive = category.CategoriesActive;
                cate.CategoriesUrl = category.CategoriesUrl;
                cate.LanguagesID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()); //category.LanguagesID;
                cate.CategoriesParentID = category.CategoriesParentID;
                cate.SiteGuid = DefaultSiteGuidGetter();
                cate.Images = category.Images;
                cateId = Models.ArticaleMasterModel.CreateArticleCategory(cate);

                ViewData["Result"] = "Create Article Category Success!";

            }
            catch
            {
                return View("DetailArticleCategory", new Models.Collection.ArticleCategoryCollection());     //return to detail
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/ArticaleMaster/EditArticleCategory/" + cateId);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult EditArticleCategory(int id)
        {
            ViewData["IsAdd"] = false;
            int siteGuid = GetSiteGuid();
            
            Article_Category cate = Models.ArticaleMasterModel.GetArticleCategory(id);
            var category = new Models.Collection.ArticleCategoryCollection();
            category.CategoriesID = cate.CategoriesID;
            category.CategoriesName = cate.CategoriesName;
            category.CategoriesAlias = cate.CategoriesAlias;
            category.CategoriesAccess = cate.CategoriesAccess;
            category.CategoriesParams = cate.CategoriesParams;
            category.CategoriesOrdering = cate.CategoriesOrdering;
            if (cate.CategoriesActive != null)
            {
                category.CategoriesActive = (bool)cate.CategoriesActive;
            }
            
            category.CategoriesUrl = cate.CategoriesUrl;

            if (cate.LanguagesID != null)
            {
                category.LanguagesID = cate.LanguagesID;
            }

            if (cate.CategoriesParentID != null)
            {
                category.CategoriesParentID = (int)cate.CategoriesParentID;
            }

            category.Images = cate.Images;

            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", cate.LanguagesID != null ? cate.LanguagesID : 0);
            ViewData["ListParent"] = new SelectList(GetListArticleCategoryDropBasic(null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid,null), "CategoriesID", "CategoriesName", cate.CategoriesParentID != 0 ? cate.CategoriesParentID : 0);
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailArticleCategory", category);      ///return to detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEdit(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            var category = new Models.Collection.ArticleCategoryCollection();
            TryUpdateModel(category);
            int siteGuid = GetSiteGuid();
            
            try
            {

                //Update ArticleCategory
                SCSService.Article_Category cate = Models.ArticaleMasterModel.GetArticleCategory(category.CategoriesID);
                cate.CategoriesName = category.CategoriesName;
                if (category.CategoriesName != string.Empty)
                {
                    string inputString = baseSvc.ConvertString(category.CategoriesName);
                    Regex re = new Regex("[;\\\\/:*?\"<>|&']");
                    string outputString = re.Replace(inputString, "-");
                    cate.CategoriesAlias = outputString;
                }
                
                if (category.CategoriesAccess != null)
                {
                    cate.CategoriesAccess = (int)category.CategoriesAccess;
                }
                else
                {
                    //cate.CategoriesAccess = 0;
                }

                cate.CategoriesParams = category.CategoriesParams;
                if (category.CategoriesOrdering != null)
                {
                    cate.CategoriesOrdering = (int)category.CategoriesOrdering; 
                }
                
                cate.CategoriesActive = category.CategoriesActive;
                cate.CategoriesUrl = category.CategoriesUrl;
                cate.LanguagesID = category.LanguagesID;
                if (category.CategoriesParentID != null)
                {
                    cate.CategoriesParentID = category.CategoriesParentID;
                }
                
                cate.SiteGuid = DefaultSiteGuidGetter();
                cate.Images = category.Images;

                //Call Update method
                Models.ArticaleMasterModel.UpdateArticleCategory(cate);

                ViewData["Result"] = "Update ArticleCategory Success!";

            }
            catch
            {
                return View("", new Models.Collection.ArticleCategoryCollection());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + StockModel.GetLanguageByID(int.Parse(collection.Get("LanguagesID"))).countryCode + "/ArticaleMaster/EditArticleCategory/" + category.CategoriesID);
        }


        public List<Article_Category> GetListArticleCategoryDropBasic(string CategoriesName, string CategoriesAlias, string CategoriesParams, int? CategoriesOrdering, bool? CategoriesActive, string CategoriesUrl, int? id, int LanguagesID, int siteGuid,string images)
        {
            List<Article_Category> sb = new List<Article_Category>();
            return ListArticleCategoryDropBasic(CategoriesName, CategoriesAlias, CategoriesParams, CategoriesOrdering, CategoriesActive, CategoriesParams, ref sb, id, true, LanguagesID, siteGuid,images);
        }

        public List<Article_Category> ListArticleCategoryDropBasic(string CategoriesName, string CategoriesAlias, string CategoriesParams, int? CategoriesOrdering, bool? CategoriesActive, string CategoriesUrl, ref List<Article_Category> sb, int? id, bool root, int LanguagesID, int siteGuid,string images)
        {
            List<SCSService.Article_Category> listcate = Models.ArticaleMasterModel.GetListArticalCategoryByParentIDSearch(id, LanguagesID, siteGuid, CategoriesName, CategoriesAlias, CategoriesParams, CategoriesOrdering, CategoriesActive, CategoriesUrl,images);

            foreach (var item in listcate)
            {
                if (!root)
                {
                    item.CategoriesName = Models.ArticaleMasterModel.GetArticleCategory((int)item.CategoriesParentID).CategoriesName + ">>" + item.CategoriesName;

                    Article_Category ac = Models.ArticaleMasterModel.GetArticleCategory((int)id);
                    foreach (var itemStr in sb)
                    {
                        if (itemStr.CategoriesID == ac.CategoriesID)
                        {
                            if (itemStr.CategoriesName.Contains(">>"))
                            {
                                int laststr = itemStr.CategoriesName.LastIndexOf(">>") + 2;
                                string addStr = itemStr.CategoriesName.Substring(0, laststr);
                                item.CategoriesName = addStr + item.CategoriesName;
                            }
                        }
                    }
                }


                sb.Add(item);
                List<SCSService.Article_Category> listChild = Models.ArticaleMasterModel.GetListArticalCategoryByParentIDSearch(item.CategoriesID,LanguagesID,siteGuid,CategoriesName,CategoriesAlias,CategoriesParams,CategoriesOrdering,CategoriesActive,CategoriesUrl,images);
                if (listChild.Count() > 0)
                {
                    ListArticleCategoryDropBasic(CategoriesName,CategoriesAlias,CategoriesParams,CategoriesOrdering,CategoriesActive,CategoriesUrl, ref sb, item.CategoriesID, false, LanguagesID, siteGuid,images);
                }

            }

            return sb;
        }

        public StringBuilder GetListArticleCategoryBuilder(int? id, int LanguageID, int siteGuid)
        {
            StringBuilder sb = new StringBuilder();
            return ListArticleCategoryBuilder(ref sb, id, true, LanguageID, siteGuid);
        }

        public StringBuilder ListArticleCategoryBuilder(ref StringBuilder sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Article_Category> listcate = Models.ArticaleMasterModel.GetListArticleCategoryByParentId(id, LanguagesID, siteGuid);
            if (root)
            {
                sb.Append("<ul id='navigation'>" + "List Article Category");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listcate)
            {
                sb.Append("<li><a href='/" + siteGuid + "/" + StockModel.GetLanguageByID(LanguagesID).countryCode + "/ArticaleMaster/EditArticleCategory/" + item.CategoriesID + "'>" + item.CategoriesName + "</a>");
                List<SCSService.Article_Category> listChild = Models.ArticaleMasterModel.GetListArticleCategoryByParentId(item.CategoriesID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListArticleCategoryBuilder(ref sb, item.CategoriesID, false, LanguagesID, siteGuid);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public ActionResult ChangeStatusArticleCategory(int? id, bool? proid)
        {
            Models.ArticaleMasterModel.UpdateStatusArticleCategory(id, proid);
            string outStr = "" + proid;
            return Json(outStr);
        }

        public ActionResult UdpateSortIndex(int? id, int? proid)
        {
            Models.ArticaleMasterModel.UpdateSortOrderArticleCategory(id, proid);
            string result = "" + proid;
            return Json(result);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.ArticleCategoryViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.ArticleCategoryViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        public static SelectList SetOrder(int langauesID, int siteGuid)
        {

            int count = Models.ArticaleMasterModel.GetCountArticleCategory(langauesID, siteGuid);
            var tp = new List<string> { };
            for (int i = 1; i < (count + 1); i++)
            {
                tp.Add("" + i);
            }
            return new SelectList(tp);
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListArticleCategory(string SCategoriesName, string SCategoriesAlias, string SCategoriesParams, int? SCategoriesOrdering, bool? SCategoriesActive, string SCategoriesUrl, string images)
        {
            int currentPage = 1;
            int pageSize = 20;
            string sortField = "CategoriesOrdering";
            string sortDirection = "Asc";

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid =GetSiteGuid();
            
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            ViewData["ListArticleCategory"] = GetListArticleCategoryBuilder(null, LanguageID, siteGuid);
            ViewData["SetOrder"] = SetOrder(LanguageID, siteGuid);

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListArticleCategory(SCategoriesName, SCategoriesAlias, SCategoriesParams, SCategoriesOrdering, SCategoriesActive, SCategoriesUrl, currentPage, pageSize, sortField, sortDirection, null, siteGuid, images);


        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListArticleCategory(string SCategoriesName, string SCategoriesAlias, string SCategoriesParams, int? SCategoriesOrdering, bool? SCategoriesActive, string SCategoriesUrl, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? siteGuid, string images)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 20;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;
            ViewData["ListArticleCategory"] = GetListArticleCategoryBuilder(null, LanguageID, (int)siteGuid);
            ViewData["SetOrder"] = SetOrder(LanguageID, (int)siteGuid);

            var query = GetListArticleCategoryDropBasic(SCategoriesName, SCategoriesAlias, SCategoriesParams, SCategoriesOrdering, SCategoriesActive, SCategoriesUrl, null, LanguageID, (int)siteGuid, images).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Article_Category), "Article_Category");
                var sortExpression = Expression.Lambda<Func<Article_Category, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }

            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Article_Category>();

            // Set up our ViewModel
            var viewModel = new ArticleCategoryViewModels
            {
                ArticleCategoryList = result,
                SCategoriesName = SCategoriesName,
                SCategoriesAlias = SCategoriesAlias,
                SCategoriesParams = SCategoriesParams,
                SCategoriesActive = SCategoriesActive,
                SCategoriesOrdering = SCategoriesOrdering,
                SCategoriesUrl = SCategoriesUrl,
                Images=images
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }
        public static bool CheckDeleteArticleCategory(int id)
        {
            int count = Models.ArticaleMasterModel.GetCountArticleInArticleCategory(id);
            return count > 0 ? false : true;
        }

        public ActionResult DeleteArticleCategory(int id, string returnUrl)
        {
            if (CheckDeleteArticleCategory(id))
            {
                Models.ArticaleMasterModel.DeleteArticleCategory(id);
                ViewData["Result"] = "Delete success!";
            }
            else
                ViewData["Result"] = "ArticalCategory have articles. You can't delete";

            return Redirect(returnUrl);
        }
        #endregion

        #region "Article"
        public ActionResult ChangeStatusArticle(int? id, bool? proid)
        {
            Models.ArticaleMasterModel.UpdateArticleStatus(id, proid);

            string outStr = "" + proid;
            return Json(outStr);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult CreateArticle()
        {
            var article = new Models.Collection.ArticleCollection();
            article.Active = true; //default true
            int siteGuid = GetSiteGuid();


            ViewData["IsAdd"] = true;

            ViewData["ListArticleCategoryDrop"] = new SelectList(GetListArticleCategoryDropBasic(null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid ,null), "CategoriesID", "CategoriesName");


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailArticle", article);   //Return Article Detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddArticle(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            var article = new Models.Collection.ArticleCollection();
            TryUpdateModel(article);
            int artID = 0;
            try
            {
                if (article.ArrayArticleCategoryID != "" && article.ArrayArticleCategoryID!=null)
                {
                    //Create Article
                    SCSService.Article art = new Article();
                    art.Title = article.Title;
                    if (article.Title != string.Empty)
                    {
                        string inputString = baseSvc.ConvertString(article.Title);
                        Regex re = new Regex("[;\\\\/:*?\"<>|&']");
                        string outputString = re.Replace(inputString, "-");
                        art.Alias = outputString;
                    }
                    art.IntroText = article.IntroText;
                    art.FullText = article.FullText;
                    art.Images = article.Images;
                    art.Created =DateTime.Now;
                    art.CreatedBy = int.Parse(Session["UserID"].ToString());
                    //art.Modified = article.Modified;
                    //art.ModifiedBy = article.ModifiedBy;
                    art.Url = article.Url;                 
                    art.Version = article.Version;                                    
                    art.Hits = article.Hits;                  
                    art.Ordering = article.Ordering;                    
                    art.Active = article.Active;                                      
                    art.MetaKey = article.MetaKey;
                    art.MetaDesc = article.MetaDesc;
                    art.MetaData = article.MetaData;
                    art.Attribs = article.Attribs;
                    art.Access = article.Access;
                    art.CheckedOut = article.CheckedOut;

                    if (article.CheckedOutTime != null)
                    {
                        art.CheckedOutTime = article.CheckedOutTime;
                    }

                    if (article.PublicUp != null)
                    {
                        art.PublicUp = article.PublicUp;
                    }

                    if (article.PublicDown != null)
                    {
                        art.PublicDown = article.PublicDown;
                    }
                    
                    art.Tags = article.Tags;
                    art.Related = article.Related;

                    artID = Models.ArticaleMasterModel.CreateArticle(art);

                    if (artID > 0)
                    {
                        var arr = article.ArrayArticleCategoryID.ToString().Split(',');
                        foreach (var item in arr)
                        {
                            //Add Article to Article_Frontpage
                            SCSService.Article_Frontpage front = new Article_Frontpage();
                            front.ArticleID = artID;
                            front.CategoriesID = int.Parse(item);
                            
                            Models.ArticaleMasterModel.CreateArticleFrontpage(front);
                        }
                    }

                    ViewData["Result"] = "Create Article Success!";
                    var Cate = ArticaleMasterModel.GetListArticleFrontpageByArticleID(artID).FirstOrDefault() == null ? "" : ArticaleMasterModel.GetListArticleFrontpageByArticleID(artID).FirstOrDefault().CategoriesID.ToString();
                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/ArticaleMaster/ListArticles/" + Cate);
                }
                else
                {
                    ViewData["Result"] = "Please Choice Article Category !";
                    return View("DetailArticle", article); //return Detail Article
                }

            }
            catch
            {
                return View("DetailArticle", new Models.Collection.ArticleCollection());     //return Detail Article
            }

        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult EditArticle(int id)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
           
            var art = Models.ArticaleMasterModel.GetArticleByID(id);
            var article = new Models.Collection.ArticleCollection();
            var listCateID = Models.ArticaleMasterModel.GetListArticleCategoryIDFrontpageByArticleID(id);
            //var listTypeID = Models.StockModel.GetListTypeProductIdManageByProductID(id);
            IEnumerable<int> seleteds = listCateID.ToList();

            article.Title = art.Title;
            article.Alias = art.Alias;
            article.IntroText = art.IntroText;
            article.FullText = art.FullText;
            article.Images = art.Images;
            article.Created = art.Created;
            article.CreatedBy = art.CreatedBy;
            article.Modified = art.Modified;
            article.ModifiedBy = art.ModifiedBy;
            article.Url = art.Url;
            article.Version = art.Version;
            article.Hits = art.Hits;
            article.Ordering = art.Ordering;
            article.Active = art.Active;
            article.MetaKey = art.MetaKey;
            article.MetaDesc = art.MetaDesc;
            article.MetaData = art.MetaData;
            article.Attribs = art.Attribs;
            article.Access = art.Access;
            article.CheckedOut = art.CheckedOut;
            article.CheckedOutTime = art.CheckedOutTime;
            article.PublicUp = art.PublicUp;
            article.PublicDown = art.PublicDown;
            article.Tags = art.Tags;
            article.Related = art.Related;
            article.ArticleID = art.ArticleID;

            string arrId = "";
            foreach (var item in listCateID)
            {
                arrId += item + ",";
            }
            article.ArrayArticleCategoryID = arrId.Length > 1 ? arrId.Substring(0, arrId.LastIndexOf(',')) : "";
           
            ViewData["IsAdd"] = false;

            ViewData["ListArticleCategoryDrop"] = new MultiSelectList(GetListArticleCategoryDropBasic(null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid, null), "CategoriesID", "CategoriesName");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailArticle", article);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditArticle(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            var article = new Models.Collection.ArticleCollection();
            TryUpdateModel(article);
            int siteGuid = GetSiteGuid();
            
            try
            {

                //Update Product
                SCSService.Article art = Models.ArticaleMasterModel.GetArticleByID(article.ArticleID);
                art.Title = article.Title;
                if (article.Title!=string.Empty)
                {
                    string inputString = baseSvc.ConvertString(article.Title);
                    Regex re = new Regex("[;\\\\/:*?\"<>|&']");
                    string outputString = re.Replace(inputString, "-");
                    art.Alias = outputString;
                }
                
                art.IntroText = article.IntroText;
                art.FullText = article.FullText;
                art.Images = article.Images;
                art.Created = article.Created;
                art.CreatedBy = article.CreatedBy;
                art.Modified = article.Modified;
                art.ModifiedBy = article.ModifiedBy;
                art.Url = article.Url;
                art.Version = article.Version;
                art.Hits = article.Hits;
                art.Ordering = article.Ordering;
                art.Active = article.Active;
                art.MetaKey = article.MetaKey;
                art.MetaDesc = article.MetaDesc;
                art.MetaData = article.MetaData;
                art.Attribs = article.Attribs;
                art.Access = article.Access;
                art.CheckedOut = article.CheckedOut;
                art.CheckedOutTime = article.CheckedOutTime;
                art.PublicUp = article.PublicUp;
                art.PublicDown = article.PublicDown;
                art.Tags = article.Tags;
                art.Related = article.Related;

                //Call Update method
                Models.ArticaleMasterModel.UpdateArticle(art);

                //Update Article_Frontpage
                //Check List . If Category in list Unchecked All ==> Not Update

                if (article.ArrayArticleCategoryID != "")
                {
                    //Delete all Article in Article_Frontpage
                    var list = Models.ArticaleMasterModel.GetListArticleFrontpageByArticleID(art.ArticleID);
                    foreach (var item in list)
                    {
                        Models.ArticaleMasterModel.DeleteArticleFrontpage(item.ArticleID,item.CategoriesID);
                    }

                    //Create Article_Frontpage New
                    //int manaID = 0;

                    var arr = article.ArrayArticleCategoryID.ToString().Split(',');
                    foreach (var item in arr)
                    {
                        //Add Article to Article_Frontpage
                        SCSService.Article_Frontpage front = new Article_Frontpage();
                        front.ArticleID = art.ArticleID;
                        front.CategoriesID = int.Parse(item);
                        
                        Models.ArticaleMasterModel.CreateArticleFrontpage(front);
                    }
                    ViewData["Result"] = "Update Article Success!";

                    //return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/ArticaleMaster/ListArticles/" + art.ArticleID);
                    var Cate = ArticaleMasterModel.GetListArticleFrontpageByArticleID(art.ArticleID).FirstOrDefault() == null ? "" : ArticaleMasterModel.GetListArticleFrontpageByArticleID(art.ArticleID).FirstOrDefault().CategoriesID.ToString();
                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/ArticaleMaster/ListArticles/" + Cate);
                }
                else
                {
                    ViewData["Result"] = "Update Article failed!";
                    return View("DetailArticle", article);
                }
            }
            catch
            {
                return View("DetailArticle", new Models.Collection.ArticleCollection());
            }
            
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.ListArticleViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.ListArticleViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListArticles(int? id, string TitleSearch, string IntroTextSearch, string FullTextSearch)
        {
            //Id đầu vào là cateId
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "ArticleID";
            string sortDirection = "Asc";

            int siteGuid = GetSiteGuid();
            
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListArticles(TitleSearch, IntroTextSearch,FullTextSearch, currentPage, pageSize, sortField, sortDirection, null, id, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListArticles(string TitleSearch, string IntroTextSearch, string FullTextSearch, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là cateId
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 2000;
            }

            if (siteGuid == null)
            {

                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;

            
            var query = Models.ArticaleMasterModel.GetListArticleByCategoryID(id, LanguageID, (int)siteGuid,TitleSearch,IntroTextSearch,FullTextSearch).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Article), "Article");
                var sortExpression = Expression.Lambda<Func<Article, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Article>();


            // Set up our ViewModel
            var viewModel = new ListArticleViewModels
            {
                ArticleItem = result,
                ArticleCategory = id != null ? Models.ArticaleMasterModel.GetArticleCategory((int)id) : null,
                TitleSearch = TitleSearch,
                IntroTextSearch = IntroTextSearch,
                FullTextSearch=FullTextSearch
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }

        public ActionResult DeleteArticle(int id, string returnUrl)
        {
           Models.ArticaleMasterModel.DeleteArticle(id);
           ViewData["Result"] = "Delete success!";
            
            return Redirect(returnUrl);
        }
        #endregion      

        #region "Article Static"
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AddArticleStatic()
        {
            var artStatic = new Models.Collection.ArticleStaticCollection();
            artStatic.Active = true;
            int siteGuid = GetSiteGuid();
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());


            ViewData["IsAdd"] = true;
            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", languageId);
            ViewData["ListArticleStaticCategoryDrop"] = new SelectList(GetListStaticArticleCategoryDropBasic(null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid, null), "StaticCategoryID", "StaticCategoryName");


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailArticleStatic", artStatic);      ///Return to view detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddArticleStatic(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var artStatic = new Models.Collection.ArticleStaticCollection();
            TryUpdateModel(artStatic);
            int artId = 0;
            try
            {

                //Create ArticleCategory
                SCSService.Article_Static art = new Article_Static();
                art.StaticName = artStatic.StaticName;
                art.StaticIntroText = artStatic.StaticIntroText;
                art.StaticContent = artStatic.StaticContent;
                art.Url = artStatic.Url;
                if (artStatic.StaticName != string.Empty)
                {
                    string inputString = baseSvc.ConvertString(artStatic.StaticName);
                    Regex re = new Regex("[;\\\\/:*?\"<>|&']");
                    string outputString = re.Replace(inputString, "-");
                    art.Alias = outputString;
                }
                
                art.Active = artStatic.Active;
                art.Images = artStatic.Images;        

                artId = Models.ArticaleMasterModel.CreateArticleStatic(art);

                if (artId > 0)
                {
                    var arr = artStatic.ArrayArticleStaticCategoryID.ToString().Split(',');
                    foreach (var item in arr)
                    {
                        //Add ArticleStatic to Article_Static_Frontpage
                        SCSService.Article_Static_Frontpage front = new Article_Static_Frontpage();
                        front.StaticID = artId;
                        front.StaticCategoryID = int.Parse(item);

                        Models.ArticaleMasterModel.CreateArticleStaticFrontpage(front);
                    }
                }

                ViewData["Result"] = "Create Article Static Success!";

            }
            catch
            {
                return View("DetailArticleStatic", new Models.Collection.ArticleStaticCollection());     //return to detail
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/ArticaleMaster/EditArticleStatic/" + artId);
           
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult EditArticleStatic(int id)
        {
            ViewData["IsAdd"] = false;
            int siteGuid = GetSiteGuid();

            Article_Static art = Models.ArticaleMasterModel.GetArticleStaticByID(id);
            var artStatic = new Models.Collection.ArticleStaticCollection();
            artStatic.StaticName = art.StaticName;
            artStatic.StaticIntroText = art.StaticIntroText;
            artStatic.StaticContent = art.StaticContent;
            artStatic.Url = art.Url;
            artStatic.Alias = art.Alias;
            artStatic.Active = (bool)art.Active;
            artStatic.Images = art.Images;
            artStatic.StaticID = art.StaticID;

            var listCateID = Models.ArticaleMasterModel.GetListArticleStaticFrontpageByArticleStaticID(id);
            IEnumerable<int> seleteds = listCateID.Select(p=>p.StaticCategoryID).ToList();

            string arrId = "";
            foreach (var item in seleteds)
            {
                arrId += item + ",";
            }
            artStatic.ArrayArticleStaticCategoryID = arrId.Length > 1 ? arrId.Substring(0, arrId.LastIndexOf(',')) : "";

            ViewData["ListArticleStaticCategoryDrop"] = new SelectList(GetListStaticArticleCategoryDropBasic(null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid, null), "StaticCategoryID", "StaticCategoryName");
            //ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", art.LanguagesID != null ? art.LanguagesID : 0);
           
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailArticleStatic", artStatic);      ///return to detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditArticleStatic(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            var artStatic = new Models.Collection.ArticleStaticCollection();
            TryUpdateModel(artStatic);
            int siteGuid = GetSiteGuid();

            try
            {

                //Update ArticleStatic
                SCSService.Article_Static art = Models.ArticaleMasterModel.GetArticleStaticByID((int)artStatic.StaticID);
                art.StaticName = artStatic.StaticName;
                art.StaticIntroText = artStatic.StaticIntroText;
                art.StaticContent = artStatic.StaticContent;
                art.Url = artStatic.Url;
                if (artStatic.StaticName != string.Empty)
                {
                    string inputString = baseSvc.ConvertString(artStatic.StaticName);
                    Regex re = new Regex("[;\\\\/:*?\"<>|&']");
                    string outputString = re.Replace(inputString, "-");
                    art.Alias = outputString;
                }
                
                art.Active = artStatic.Active;
                art.Images = artStatic.Images;
               

                //Call Update method
                Models.ArticaleMasterModel.UpdateArticleStatic(art);

                //Update Article_Static_Frontpage
                //Check List . If Category in list Unchecked All ==> Not Update

                if (artStatic.ArrayArticleStaticCategoryID != "")
                {
                    //Delete all Article in Article_Static_Frontpage
                    var list = Models.ArticaleMasterModel.GetListArticleStaticFrontpageByArticleStaticID(art.StaticID);
                    foreach (var item in list)
                    {
                        Models.ArticaleMasterModel.DeleteArticleStaticFrontpage(item.StaticID, item.StaticCategoryID);
                    }

                    //Create Article_Static_Frontpage New

                    var arr = artStatic.ArrayArticleStaticCategoryID.ToString().Split(',');
                    foreach (var item in arr)
                    {
                        //Add ArticleStatic to Article_Static_Frontpage
                        SCSService.Article_Static_Frontpage front = new Article_Static_Frontpage();
                        front.StaticID = art.StaticID;
                        front.StaticCategoryID = int.Parse(item);

                        Models.ArticaleMasterModel.CreateArticleStaticFrontpage(front);
                    }
                    ViewData["Result"] = "Update Article Static Success!";
                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/ArticaleMaster/EditArticleStatic/" + art.StaticID);
                }
                else
                {
                    ViewData["Result"] = "Update Article Static failed!";
                    return View("DetailArticleStatic", artStatic);
                }

                

            }
            catch
            {
                return View("", new Models.Collection.ArticleCategoryCollection());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/ArticaleMaster/EditArticleCategory/" + artStatic.StaticID);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.ListArticleStaticViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.ListArticleStaticViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListArticleStatic(int? id,string StaticName, string StaticContent, string StaticIntroText, bool? Active)
        {
            //Id đầu vào là cateId
            int currentPage = 1;
            int pageSize = 2000;
            string sortField = "StaticID";
            string sortDirection = "Asc";

            int siteGuid = GetSiteGuid();

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListArticleStatic(id,StaticName, StaticContent, StaticIntroText,Active, currentPage, pageSize, sortField, sortDirection, null, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListArticleStatic(int? id, string StaticName, string StaticContent, string StaticIntroText, bool? Active, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 2000;
            }

            if (siteGuid == null)
            {

                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;


            var query = Models.ArticaleMasterModel.GetListArticleStatic(id,LanguageID, (int)siteGuid, StaticName, StaticIntroText, StaticContent,Active).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Article_Static), "Article_Static");
                var sortExpression = Expression.Lambda<Func<Article_Static, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Article_Static>();


            // Set up our ViewModel
            var viewModel = new ListArticleStaticViewModels
            {
                ArticleStaticItem = result,
                StaticName = StaticName,
                StaticIntroText = StaticIntroText,
                StaticContent = StaticContent,
                Active=Active
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }

        public ActionResult DeleteArticleStatic(int id, string returnUrl)
        {
            Models.ArticaleMasterModel.DeleteArticleStatic(id);
            ViewData["Result"] = "Delete success!";

            return Redirect(returnUrl);
        }

        public ActionResult ChangeStatusArticleStatic(int? id, bool? proid)
        {
            Models.ArticaleMasterModel.UpdateArticleStaticStatus(id, proid);

            string outStr = "" + proid;
            return Json(outStr);
        }
        #endregion

        #region "StaticArticleCategory"
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AddStaticArticleCategory()
        {
            var category = new Models.Collection.StaticArticalCategoryCollection();
            category.StaticCategoryActive = true;
            int siteGuid = GetSiteGuid();
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());


            ViewData["IsAdd"] = true;
            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", languageId);
            ViewData["ListParent"] = new SelectList(GetListStaticArticleCategoryDropBasic(null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid, null), "StaticCategoryID", "StaticCategoryName");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
               // return View("ListStaticArticleCategory", category);
                return View("DetailStaticlArticleCategory", category);      ///Return to view detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddStaticCategory(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var category = new Models.Collection.StaticArticalCategoryCollection();
            TryUpdateModel(category);
            int cateId = 0;
            try
            {
                //Create static ArticleCategory
                SCSService.Artilce_Static_Category cate = new Artilce_Static_Category();
                cate.StaticCategoryName = category.StaticCategoryName;
                if (category.StaticCategoryName != string.Empty)
                {
                    string inputString = baseSvc.ConvertString(category.StaticCategoryName);
                    Regex re = new Regex("[;\\\\/:*?\"<>|&']");
                    string outputString = re.Replace(inputString, "-");
                    cate.StaticCategoryAlias = outputString;
                }
                
                if (category.StaticCategoryAccess != null)
                {
                    cate.StaticCategoryAccess = (int)category.StaticCategoryAccess;
                }
                else
                {
                    cate.StaticCategoryAccess = 0;
                }

                cate.StaticCategoryParams = category.StaticCategoryParams;
                if (category.StaticCategoryOrder == null)
                {
                    cate.StaticCategoryOrder = Models.ArticaleMasterModel.GetCountStaticArticleCategory(LanguageID, GetSiteGuid()) + 1;
                }
                else
                {
                    cate.StaticCategoryOrder = (int)category.StaticCategoryOrder;
                }

                cate.StaticCategoryActive = category.StaticCategoryActive;
                cate.StaticCategoryUrl = category.StaticCategoryUrl;
                cate.LanguagesID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()); //category.LanguagesID;
                if (category.StaticCategoryParentID == 0)
                {
                    cate.StaticCategoryParentID = null;
                }
                else
                {
                    cate.StaticCategoryParentID = category.StaticCategoryParentID;
                }
                
                cate.SiteGuid = DefaultSiteGuidGetter();
                cate.Images = category.Images;
                cate.StaticCategoryActive = category.StaticCategoryActive;
                cateId = Models.ArticaleMasterModel.CreateStaticArticleCategory(cate);

                ViewData["Result"] = "Create Static Article Category Success!";
            }
            catch
            {
                return View("DetailStaticlArticleCategory", new Models.Collection.StaticArticalCategoryCollection());     //return to detail
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/ArticaleMaster/EditStaticArticleCategory/" + cateId);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult EditStaticArticleCategory(int id)
        {
            ViewData["IsAdd"] = false;
            int siteGuid = GetSiteGuid();

            Artilce_Static_Category cate = Models.ArticaleMasterModel.GetStaticArticleCategory(id);
            var category = new Models.Collection.StaticArticalCategoryCollection();
            category.StaticCategoryID = cate.StaticCategoryID;
            category.StaticCategoryName = cate.StaticCategoryName;
            category.StaticCategoryAlias = cate.StaticCategoryAlias;
            category.StaticCategoryAccess = cate.StaticCategoryAccess;
            category.StaticCategoryParams = cate.StaticCategoryParams;
            category.StaticCategoryOrder = cate.StaticCategoryOrder;
            category.StaticCategoryActive = (bool)cate.StaticCategoryActive;
            category.StaticCategoryUrl = cate.StaticCategoryUrl;

            if (cate.LanguagesID != null)
            {
                category.LanguagesID = cate.LanguagesID;
            }
            if (cate.StaticCategoryParentID != null)
            {
                category.StaticCategoryParentID = (int)cate.StaticCategoryParentID;
            }
            else
            {
                category.StaticCategoryParentID = 0;
            }
            category.Images = cate.Images;

            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", cate.LanguagesID != null ? cate.LanguagesID : 0);
            ViewData["ListParent"] = new SelectList(GetListStaticArticleCategoryDropBasic(null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid, null), "StaticCategoryID", "StaticCategoryName", cate.StaticCategoryParentID != 0 ? cate.StaticCategoryParentID : 0);
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailStaticlArticleCategory", category);      ///return to detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditStaticArticleCategory(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            var category = new Models.Collection.StaticArticalCategoryCollection();
            TryUpdateModel(category);
            int siteGuid = GetSiteGuid();

            try
            {

                //Update StaticArticleCategory
                SCSService.Artilce_Static_Category cate = Models.ArticaleMasterModel.GetStaticArticleCategory(category.StaticCategoryID);
                cate.StaticCategoryName = category.StaticCategoryName;
                if (category.StaticCategoryName != string.Empty)
                {
                    string inputString = baseSvc.ConvertString(category.StaticCategoryName);
                    Regex re = new Regex("[;\\\\/:*?\"<>|&']");
                    string outputString = re.Replace(inputString, "-");
                    cate.StaticCategoryAlias = outputString;
                }
                if (category.StaticCategoryAccess != null)
                {
                    cate.StaticCategoryAccess = (int)category.StaticCategoryAccess;
                }
                else
                {
                    //cate.CategoriesAccess = 0;
                }

                cate.StaticCategoryParams = category.StaticCategoryParams;
                if (category.StaticCategoryOrder != null)
                {
                    cate.StaticCategoryOrder = (int)category.StaticCategoryOrder;
                }

                cate.StaticCategoryActive = category.StaticCategoryActive;
                cate.StaticCategoryUrl = category.StaticCategoryUrl;
                cate.LanguagesID = category.LanguagesID;
                if (category.StaticCategoryParentID != null)
                {
                    if (category.StaticCategoryParentID == 0)
                    {
                        cate.StaticCategoryParentID = null;
                    }
                    else
                    {
                        cate.StaticCategoryParentID = category.StaticCategoryParentID;
                    }
                    
                }
                
                cate.SiteGuid = DefaultSiteGuidGetter();
                cate.Images = category.Images;
         

                //Call Update method
                Models.ArticaleMasterModel.UpdateStaticArticleCategory(cate);

                ViewData["Result"] = "Update StaticArticleCategory Success!";

            }
            catch
            {
                return View("", new Models.Collection.StaticArticalCategoryCollection());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + StockModel.GetLanguageByID(int.Parse(collection.Get("LanguagesID"))).countryCode + "/ArticaleMaster/EditStaticArticleCategory/" + category.StaticCategoryID);
        }


        public List<Artilce_Static_Category> GetListStaticArticleCategoryDropBasic(string categoriesName, string categoriesAlias, string categoriesParams, int? categoriesOrdering, bool? categoriesActive, string categoriesUrl, int? id, int LanguagesID, int siteGuid, string images)
        {
            List<Artilce_Static_Category> sb = new List<Artilce_Static_Category>();
            return GetListStaticArticleCategoryDropBasic(categoriesName, categoriesAlias, categoriesParams, categoriesOrdering, categoriesActive, categoriesParams, ref sb, id, true, LanguagesID, siteGuid, images);
        }

        public List<Artilce_Static_Category> GetListStaticArticleCategoryDropBasic(string staticcategoriesName, string staticcategoriesAlias, string staticcategoriesParams, int? staticcategoriesOrdering, bool? staticcategoriesActive, string staticcategoriesUrl, ref List<Artilce_Static_Category> sb, int? id, bool root, int LanguagesID, int siteGuid, string images)
        {
            List<SCSService.Artilce_Static_Category> listcate = Models.ArticaleMasterModel.GetListStaticArticalCategoryByParentIDSearch(id, LanguagesID, siteGuid, staticcategoriesName, staticcategoriesAlias, staticcategoriesParams, staticcategoriesOrdering, staticcategoriesActive, staticcategoriesUrl, images);

            foreach (var item in listcate)
            {
                if (!root)
                {
                    item.StaticCategoryName = Models.ArticaleMasterModel.GetStaticArticleCategory((int)item.StaticCategoryParentID).StaticCategoryName + ">>" + item.StaticCategoryName;

                    Artilce_Static_Category ac = Models.ArticaleMasterModel.GetStaticArticleCategory((int)id);
                    foreach (var itemStr in sb)
                    {
                        if (itemStr.StaticCategoryID == ac.StaticCategoryID)
                        {
                            if (itemStr.StaticCategoryName.Contains(">>"))
                            {
                                int laststr = itemStr.StaticCategoryName.LastIndexOf(">>") + 2;
                                string addStr = itemStr.StaticCategoryName.Substring(0, laststr);
                                item.StaticCategoryName = addStr + item.StaticCategoryName;
                            }
                        }
                    }

                }


                sb.Add(item);
                List<SCSService.Artilce_Static_Category> listChild = Models.ArticaleMasterModel.GetListStaticArticalCategoryByParentIDSearch(item.StaticCategoryID, LanguagesID, siteGuid, staticcategoriesName, staticcategoriesAlias, staticcategoriesParams, staticcategoriesOrdering,staticcategoriesActive, staticcategoriesUrl,images);
                if (listChild.Count() > 0)
                {
                    GetListStaticArticleCategoryDropBasic(staticcategoriesName, staticcategoriesAlias, staticcategoriesParams, staticcategoriesOrdering, staticcategoriesActive, staticcategoriesUrl, ref sb, item.StaticCategoryID, false, LanguagesID, siteGuid, images);
                }

            }

            return sb;
        }


        public StringBuilder GetListStaticArticleCategoryBuilder(int? id, int LanguageID, int siteGuid)
        {
            StringBuilder sb = new StringBuilder();
            return ListStaticArticleCategoryBuilder(ref sb, id, true, LanguageID, siteGuid);
        }

        public StringBuilder ListStaticArticleCategoryBuilder(ref StringBuilder sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Artilce_Static_Category> listcate = Models.ArticaleMasterModel.GetListStaticArticleCategoryByParentId(id, LanguagesID, siteGuid);
            if (root)
            {
                sb.Append("<ul id='navigation'>" + "List Static Article Category");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listcate)
            {
                sb.Append("<li><a href='/" + siteGuid + "/" + StockModel.GetLanguageByID(LanguagesID).countryCode + "/ArticaleMaster/EditStaticArticleCategory/" + item.StaticCategoryID + "'>" + item.StaticCategoryName + "</a>");
                List<SCSService.Artilce_Static_Category> listChild = Models.ArticaleMasterModel.GetListStaticArticleCategoryByParentId(item.StaticCategoryID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListStaticArticleCategoryBuilder(ref sb, item.StaticCategoryID, false, LanguagesID, siteGuid);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public ActionResult ChangeStatusStaticArticleCategory(int? id, bool? proid)
        {
            Models.ArticaleMasterModel.UpdateStatusStaticArticleCategory(id, proid);
            string outStr = "" + proid;
            return Json(outStr);
        }

        public ActionResult UdpateSortStaticIndex(int? id, int? proid)
        {
            Models.ArticaleMasterModel.UpdateSortOrderStaticArticleCategory(id, proid);
            string result = "" + proid;
            return Json(result);
        }

        public static string GetGridThClassStatic(ViewDataDictionary<SCS.Core.ViewModels.StaticArticleCategoryViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClickStatic(ViewDataDictionary<SCS.Core.ViewModels.StaticArticleCategoryViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        public static SelectList SetOrderStatic(int langauesID, int siteGuid)
        {

            int count = Models.ArticaleMasterModel.GetCountStaticArticleCategory(langauesID, siteGuid);
            var tp = new List<string> { };
            for (int i = 1; i < (count + 1); i++)
            {
                tp.Add("" + i);
            }
            return new SelectList(tp);
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListStaticArticleCategory(string SStaticCategoriesName, string SStaticCategoriesAlias, string SStaticCategoriesParams, int? SStaticCategoriesOrdering, bool? SStaticCategoriesActive, string SStaticCategoriesUrl, string images)
        {
            int currentPage = 1;
            int pageSize = 20;
            string sortField = "StaticCategoryOrder";
            string sortDirection = "Asc";

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            ViewData["ListStaticArticleCategory"] = GetListStaticArticleCategoryBuilder(null, LanguageID, siteGuid);
            ViewData["SetOrderStatic"] = SetOrderStatic(LanguageID, siteGuid);

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListStaticArticleCategory(SStaticCategoriesName, SStaticCategoriesAlias, SStaticCategoriesParams, SStaticCategoriesOrdering, SStaticCategoriesActive, SStaticCategoriesUrl, currentPage, pageSize, sortField, sortDirection, null, siteGuid, images);
         }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListStaticArticleCategory(string SStaticCategoriesName, string SStaticCategoriesAlias, string SStaticCategoriesParams, int? SStaticCategoriesOrdering, bool? SStaticCategoriesActive, string SStaticCategoriesUrl, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? siteGuid, string images)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 20;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;
            ViewData["ListStaticArticleCategory"] = GetListStaticArticleCategoryBuilder(null, LanguageID, (int)siteGuid);
            ViewData["SetOrderStatic"] = SetOrderStatic(LanguageID, (int)siteGuid);

            var query = GetListStaticArticleCategoryDropBasic(SStaticCategoriesName, SStaticCategoriesAlias, SStaticCategoriesParams, SStaticCategoriesOrdering, SStaticCategoriesActive, SStaticCategoriesUrl, null, LanguageID, (int)siteGuid,images).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Artilce_Static_Category), "Artilce_Static_Category");
                var sortExpression = Expression.Lambda<Func<Artilce_Static_Category, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Artilce_Static_Category>();

            // Set up our ViewModel
            var viewModel = new StaticArticleCategoryViewModels
            {
                StaticArticleCategoryList = result,
                SStaticCategoriesName = SStaticCategoriesName,
                SStaticCategoriesAlias = SStaticCategoriesAlias,
                SStaticCategoriesParams = SStaticCategoriesParams,
                SStaticCategoriesActive = SStaticCategoriesActive,
                SStaticCategoriesOrdering = SStaticCategoriesOrdering,
                SStaticCategoriesUrl = SStaticCategoriesUrl,
                Images=images
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }
        public static bool CheckDeleteStaticArticleCategory(int id)
        {
            int count = Models.ArticaleMasterModel.GetCountStaticArticleInArticleCategory(id);
            return count > 0 ? false : true;
        }

        public ActionResult DeleteStaticArticleCategory(int id, string returnUrl)
        {
            if (CheckDeleteStaticArticleCategory(id))
            {
                Models.ArticaleMasterModel.DeleteStaticArticleCategory(id);
                ViewData["Result"] = "Delete success!";
            }
            else
                ViewData["Result"] = "StaticArticalCategory have articles. You can't delete";

            return Redirect(returnUrl);
        }
        #endregion
    }
}
